package com.shao.serialize.impl;

import com.shao.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/28 14:10
 */
@Slf4j
public class JdkSerialize implements Serializer {

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            // 序列化
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("Jdk序列化对象时发生异常", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || bytes.length == 0 || clazz == null) {
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bais)) {
            Object res = ois.readObject();
            return clazz.cast(res);
        } catch (IOException | ClassNotFoundException e) {
            log.error("JDK反序列化对象时发生异常", e);
            throw new RuntimeException(e);
        }
    }
}
